package com.qf.blog.controller;

import com.qf.blog.BlogApplication;
import com.qf.blog.dto.CommentDto;
import com.qf.blog.dto.IndexPostDto;
import com.qf.blog.entity.Post;
import com.qf.blog.entity.User;
import com.qf.blog.exception.BlogException;
import com.qf.blog.service.IPostService;
import com.qf.blog.service.impl.LikeService;
import com.qf.blog.utils.Result;
import com.qf.blog.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 达哥
 * @since 2023-03-24
 */
@Controller
@RequestMapping("/post")
public class PostController {

    @Autowired
    private IPostService postService;

    @Autowired
    private LikeService likeService;


    @PostMapping("/create")
    @ResponseBody
    public Result create(@RequestBody Post post, HttpSession session) {

        // 1.获取登录用户
        User loginUser = (User) session.getAttribute("loginUser");

        if (loginUser == null) {
            throw new BlogException(104, "登录已过期，请先登录");
        }

        // 2.封装数据
        post.setUserId(loginUser.getId()); // 登录用户
        post.setCreateTime(new Date());
        post.setType(0);
        post.setScore(0.1);
        post.setStatus(0);
        post.setCommentCount(0);

        // 3.入库
        postService.save(post);

        // 4.重定向到首页
        return Result.ok();
    }

    @GetMapping("/info/{id}")
    public String info(@PathVariable Integer id, Model model, HttpSession session) {

        // 1.根据帖子id查询帖子的数据和作者信息
        IndexPostDto postDto = postService.info(id);

        // 2、根据帖子ID查询它下面的评论
        List<CommentDto> commentDtoList = postService.getCommentListByPostId(id);

        // 3.查询帖子点赞数量以及当前用户是否点赞
        Long likeCount = likeService.likeSize(id, 1);

        User loginUser = (User) session.getAttribute("loginUser");
        boolean like = false; // 默认没有点赞
        if (loginUser != null) {
            // 只有用户登录了才能判断出用户是否点赞
            like = likeService.isLike(id, 1,loginUser.getId());
        }

        // 2.把数据保存到Model中
        model.addAttribute("postDto", postDto);
        model.addAttribute("commentDtoList", commentDtoList);
        model.addAttribute("likeStatus", like ? 1 : 0);
        model.addAttribute("likeCount", likeCount);

        // 3.跳转到帖子详情页面
        return "site/discuss-detail";
    }

}
